/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Workspace;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import managedbean.JasperReport.JasperReportManagerBean;
import merlion.common.entity.DocFile;
import merlion.common.session.stateless.FileManagerSessionLocal;
import merlion.common.util.Consts;
import merlion.crm.sopm.entity.SalesQuotation;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Zhang Ying
 */
@ManagedBean
@ViewScoped
public class FileUploadManagerBean {

    @EJB
    private FileManagerSessionLocal fileManager;
    @ManagedProperty(value = "#{workspaceManagerBean}")
    private WorkspaceManagerBean workspaceManagerBean;
    @ManagedProperty(value = "#{jrManagerBean}")
    private JasperReportManagerBean reportManagerBean;
    private String tempPOID;
    
    private DocFile uploadedImg;

    /** Creates a new instance of FileUploadManagerBean */
    public FileUploadManagerBean() {
    }

    public void handleFileUploadProfile(FileUploadEvent event) {
        UploadedFile file = event.getFile();
        //application code
        DocFile myDoc = new DocFile(file.getFileName(), file.getContentType(), file.getContents());
        //Long staffId = workspaceManagerBean.getCurrentStaff().getId();
        Long staffId = workspaceManagerBean.getCurrentStaff().getId();
        if (fileManager.saveProfilePicture(staffId, myDoc)) {
            workspaceManagerBean.updateCurrentStaff();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Successful", "Profile page updated."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful", "Profile page not updated."));
        }
    }

    public void handleFileUploadPO(FileUploadEvent event) {
        System.out.println("temppo id: " + tempPOID);
        UploadedFile file = event.getFile();
        //application code
        DocFile myDoc = new DocFile(file.getFileName(), file.getContentType(), file.getContents());
        if (fileManager.uploadFileIntoPurchaseOrder(myDoc, tempPOID)) {
            myDoc = fileManager.getDocFilePO(tempPOID);
            setUploadedImg(myDoc);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Successful", "Purchase order hard copy uploaded."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessfully", "Purchase order hard copy uploaded unsuccessfully."));
        }
    }
    
    public void handleFileUploadSI(FileUploadEvent event) {
        System.out.println("temppo id: " + tempPOID);
        UploadedFile file = event.getFile();
        //application code
        DocFile myDoc = new DocFile(file.getFileName(), file.getContentType(), file.getContents());
        if (fileManager.uploadFileIntoSalesInquiry(myDoc, tempPOID)) {
            myDoc = fileManager.getDocFileSI(tempPOID);
            setUploadedImg(myDoc);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Successful", "Request for sales inquiry uploaded."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessfully", "Request for sales inquiry uploaded unsuccessfully."));
        }
    }
    
    public void handleFileUploadSQ(FileUploadEvent event) {
        System.out.println("temppo id: " + tempPOID);
        UploadedFile file = event.getFile();
        //application code
        DocFile myDoc = new DocFile(file.getFileName(), file.getContentType(), file.getContents());
        if (fileManager.uploadFileIntoSalesQuotation(myDoc, tempPOID)) {
            myDoc = fileManager.getDocFileSQ(tempPOID);
            setUploadedImg(myDoc);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, "Successful", "Sales quotation uploaded."));
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessfully", "Sales quotation uploaded unsuccessfully."));
        }
    }

    public String passResult(String result) {
        String[] trims = result.split(" ");
        tempPOID = trims[4];
        System.out.println("trims 4: "+ tempPOID);
        return null;
    }

    public boolean profileShouldRendered() {
        return fileManager.haveProfilePage(workspaceManagerBean.getCurrentStaff().getId());
    }
    
    public String sendSQToCustomerTest(){
        sendSalesQuotation("winterbells815@gmail.com", new Long(10154), reportManagerBean.getReportFile(fileManager.getSalesQuotationById(10154L)));
        return null;
    }
    
    public String sendSalesQuotation(String email, Long id){
        sendSalesQuotation(email, id, reportManagerBean.getReportFile(fileManager.getSalesQuotationById(id)));
        return null;
    }
    
    public String sendRawMaterialPurchaseOrder(String email , Long id) {
        sendRawMaterialPurchaseOrder(email, id, reportManagerBean.getReportFile(fileManager.getRawMaterialPurchaseOrderById(id)));
        return null;
    }
    
    public String sendSalesOrder(String email, Long id) {
        sendSalesOrder(email, id, reportManagerBean.getReportFile(fileManager.getSalesOrderById(id)));
        return null;
    }
    
    public String sendInvoice(String email, Long id) {
        sendInvoice(email, id, reportManagerBean.getReportFile(fileManager.getInvoiceById(id)));
        return null;
    }
    
    public String sendReceipt(String email, Long id) {
        sendReceipt(email, id, reportManagerBean.getReportFile(fileManager.getReceiptById(id)));
        return null;
    }
    
    public String returnUploadedDocFileId() {
        if (getUploadedImg() == null) {
            return "";
        }
        return getUploadedImg().getId().toString();
    }
    
    public boolean renderUploadedDocFile() {
        if (getUploadedImg() != null) {
            return true;
        } else {
            return false;
        }
    }

    public Long getProfileImageId() {
        return fileManager.getProfileImage(workspaceManagerBean.getCurrentStaff().getId()).getId();
    }

    // getters and setters
    public WorkspaceManagerBean getWorkspaceManagerBean() {
        return workspaceManagerBean;
    }

    public void setWorkspaceManagerBean(WorkspaceManagerBean workspaceManagerBean) {
        this.workspaceManagerBean = workspaceManagerBean;
    }

    public JasperReportManagerBean getReportManagerBean() {
        return reportManagerBean;
    }

    public void setReportManagerBean(JasperReportManagerBean reportManagerBean) {
        this.reportManagerBean = reportManagerBean;
    }

    public DocFile getUploadedImg() {
        return uploadedImg;
    }

    public void setUploadedImg(DocFile uploadedImg) {
        this.uploadedImg = uploadedImg;
    }
    
    // for sending pdf report
    
    private void sendSalesQuotation(String emailAddr, Long sqId, byte[] contents) {
        // send the email to MDB
        try {
            Context c = new InitialContext();
            ConnectionFactory cf = (ConnectionFactory) c.lookup("jms/queueSendEmailFactory");
            Connection conn = null;
            Session s = null;


            try {
                conn = cf.createConnection();
                s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
                Destination destination = (Destination) c.lookup("jms/queueSendEmail");
                MessageProducer mp = s.createProducer(destination);
                MapMessage mmsg = s.createMapMessage();
                mmsg.setString("token", null);
                mmsg.setString("username", null);
                mmsg.setString("password", null);
                mmsg.setString("email", emailAddr);
                mmsg.setString("type", Consts.EMAIL_SQ);
                mmsg.setLong("sqId", sqId);
                mmsg.setBytes("sqContents", contents );

                mp.send(mmsg);
            } catch (JMSException jmsEx) {
                jmsEx.printStackTrace();;
            } finally {
                if (s != null) {
                    s.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (NamingException namingEx) {
            namingEx.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void sendRawMaterialPurchaseOrder(String emailAddr, Long rmpoId, byte[] contents) {
        // send the email to MDB
        try {
            Context c = new InitialContext();
            ConnectionFactory cf = (ConnectionFactory) c.lookup("jms/queueSendEmailFactory");
            Connection conn = null;
            Session s = null;


            try {
                conn = cf.createConnection();
                s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
                Destination destination = (Destination) c.lookup("jms/queueSendEmail");
                MessageProducer mp = s.createProducer(destination);
                MapMessage mmsg = s.createMapMessage();
                mmsg.setString("token", null);
                mmsg.setString("username", null);
                mmsg.setString("password", null);
                mmsg.setString("email", emailAddr);
                mmsg.setString("type", Consts.EMAIL_RMPO);
                mmsg.setLong("rmpoId", rmpoId);
                mmsg.setBytes("rmpoContents", contents );

                mp.send(mmsg);
            } catch (JMSException jmsEx) {
                jmsEx.printStackTrace();;
            } finally {
                if (s != null) {
                    s.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (NamingException namingEx) {
            namingEx.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void sendSalesOrder(String emailAddr, Long soId, byte[] contents) {
        // send the email to MDB
        try {
            Context c = new InitialContext();
            ConnectionFactory cf = (ConnectionFactory) c.lookup("jms/queueSendEmailFactory");
            Connection conn = null;
            Session s = null;


            try {
                conn = cf.createConnection();
                s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
                Destination destination = (Destination) c.lookup("jms/queueSendEmail");
                MessageProducer mp = s.createProducer(destination);
                MapMessage mmsg = s.createMapMessage();
                mmsg.setString("token", null);
                mmsg.setString("username", null);
                mmsg.setString("password", null);
                mmsg.setString("email", emailAddr);
                mmsg.setString("type", Consts.EMAIL_SO);
                mmsg.setLong("soId", soId);
                mmsg.setBytes("soContents", contents );

                mp.send(mmsg);
            } catch (JMSException jmsEx) {
                jmsEx.printStackTrace();;
            } finally {
                if (s != null) {
                    s.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (NamingException namingEx) {
            namingEx.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void sendInvoice(String emailAddr, Long invId, byte[] contents) {
        // send the email to MDB
        try {
            Context c = new InitialContext();
            ConnectionFactory cf = (ConnectionFactory) c.lookup("jms/queueSendEmailFactory");
            Connection conn = null;
            Session s = null;


            try {
                conn = cf.createConnection();
                s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
                Destination destination = (Destination) c.lookup("jms/queueSendEmail");
                MessageProducer mp = s.createProducer(destination);
                MapMessage mmsg = s.createMapMessage();
                mmsg.setString("token", null);
                mmsg.setString("username", null);
                mmsg.setString("password", null);
                mmsg.setString("email", emailAddr);
                mmsg.setString("type", Consts.EMAIL_INV);
                mmsg.setLong("invId", invId);
                mmsg.setBytes("invContents", contents );

                mp.send(mmsg);
            } catch (JMSException jmsEx) {
                jmsEx.printStackTrace();;
            } finally {
                if (s != null) {
                    s.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (NamingException namingEx) {
            namingEx.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void sendReceipt(String emailAddr, Long recId, byte[] contents) {
        // send the email to MDB
        try {
            Context c = new InitialContext();
            ConnectionFactory cf = (ConnectionFactory) c.lookup("jms/queueSendEmailFactory");
            Connection conn = null;
            Session s = null;


            try {
                conn = cf.createConnection();
                s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
                Destination destination = (Destination) c.lookup("jms/queueSendEmail");
                MessageProducer mp = s.createProducer(destination);
                MapMessage mmsg = s.createMapMessage();
                mmsg.setString("token", null);
                mmsg.setString("username", null);
                mmsg.setString("password", null);
                mmsg.setString("email", emailAddr);
                mmsg.setString("type", Consts.EMAIL_REC);
                mmsg.setLong("recId", recId);
                mmsg.setBytes("recContents", contents );

                mp.send(mmsg);
            } catch (JMSException jmsEx) {
                jmsEx.printStackTrace();;
            } finally {
                if (s != null) {
                    s.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }
        } catch (NamingException namingEx) {
            namingEx.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    
}
